<template>
  <div class="todolist">
    <h4 class="todolist-title">你好，{{ user_name }}</h4>
    <el-row>
      <el-col :xs="{span:17,offset:1}" :sm="{span:6,offset:8}">
        <el-input
          size="small"
          placeholder="请输入待办事项"
          v-model="addtodotxt"
          clearable
          @keyup.enter.native="addTodo"
        ></el-input>
      </el-col>
      <el-col :xs="{span:4,offset:1}" :sm="{span:2}" class="addbtn">
        <el-button size="small" type="primary" @click="addTodo">确定</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="{span:22,offset:1}" :sm="{span:8,offset:8}">
        <el-tabs :tab-position="tabPosition" style="height: 200px;">
          <el-tab-pane label="待完成事项">
            <List
              :todolist='true'
              :listitems='lists'
              @update-fn='updateFn'
              @delete-fn="deleteFn"
              :nolisttxt='listsingnotxt'
              :is-zero='doingCount'
            ></List>
          </el-tab-pane>
          <el-tab-pane label="已完成事项">
            <List
              :todolist='false'
              :listitems='lists'
              @update-fn='updateFn'
              :nolisttxt='listsednotxt'
              :is-zero='doneCount'
            ></List>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import List from './List'
import jwt from 'jsonwebtoken'
export default {
  created () {
    const userInfo = this.getUserInfo()
    console.log('userInfo:', userInfo)
    if (userInfo) {
      this.user_name = userInfo.name
      this.user_id = userInfo.id
    } else {
      this.user_name = ''
      this.user_id = ''
    }
    this.getTodolist()
  },
  data () {
    return {
      user_name: '',
      user_id: '',
      addtodotxt: '',
      tabPosition: 'top',
      lists: [
        // {id: 1, 'content': '看书', 'status': true},
        // {id: 2, 'content': '写字', 'status': false}
      ],
      listsingnotxt: '暂无待办事项',
      listsednotxt: '暂无完成事项'
    }
  },
  methods: {
    addTodo: function () {
      if (this.addtodotxt) {
        let aEvent = {
          'content': this.addtodotxt,
          'status': false,
          'user_id': this.user_id
        }
        this.$ajax.post('/api/todolist', aEvent)
          .then((res) => {
            if (res.status === 200) {
              this.$message({
                showClose: true,
                message: '添加成功！',
                type: 'success',
                duration: '1500'
              })
              this.getTodolist()
            } else {
              this.$message.error('创建失败')
            }
          }, (err) => {
            this.$message.error('创建失败')
            console.log(err)
          })
        // this.lists.push(aEvent)
        this.addtodotxt = ''
      } else {
        this.$message({
          showClose: true,
          message: '先输入事项哦',
          type: 'warning',
          duration: '1500'
        })
      }
    },
    deleteFn: function (index) {
      this.$ajax.delete('/api/todolist/' + this.user_id + '/' + this.lists[index].id)
        .then((res) => {
          if (res.status === 200) {
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'warning',
              duration: '1500'
            })
            this.getTodolist()
          } else {
            this.$message.error('删除失败！')
          }
        }, (err) => {
          this.$message.error('删除失败！')
          console.log(err)
        })
    },
    updateFn: function (index) {
      this.$ajax.put('/api/todolist/' + this.user_id + '/' + this.lists[index].id + '/' + this.lists[index].status)
        .then((res) => {
          if (res.data.success && res.data.message === '更新成功') {
            this.$message({
              showClose: true,
              message: '状态更新成功！',
              type: 'success',
              duration: '1500'
            })
            this.getTodolist()
          } else {
            this.$message.error('状态更新失败')
          }
        }, (err) => {
          this.$message.error('状态更新失败')
          console.log(err)
        })
    },
    getUserInfo: function () {
      const token = sessionStorage.getItem('todolist-token')
      if (token !== null && token !== 'null') {
        let decode = jwt.decode(token)
        return decode
      } else {
        return null
      }
    },
    getTodolist: function () {
      this.$ajax.get('/api/todolist/' + this.user_id)
        .then((res) => {
          if (res.status === 200) {
            this.lists = res.data
          } else {
            this.$message.error('获取列表失败！')
          }
        }, (err) => {
          this.$message.error('获取列表失败！')
          console.log(err)
        })
    },
    computedCount: function (status) {
      let count = 0
      let len = this.lists.length
      for (let index = 0; index < len; index++) {
        if (this.lists[index].status === status) {
          count += 1
        }
      }
      if (count) {
        return false
      } else {
        return true
      }
    }
  },
  computed: {
    doingCount () {
      let done = this.computedCount(0)
      return done
    },
    doneCount () {
      let done = this.computedCount(1)
      return done
    }
  },
  components: {
    List
  }
}
</script>

<style lang="scss" scoped>
  .todolist-title{
    margin-bottom: 12px;
    font-size: 16px;
  }
  .addbtn{
    text-align: right;
  }
</style>
